package com.tang.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tang.reggie.common.R;
import com.tang.reggie.pojo.Employee;
import com.tang.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     * @param session
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R login(HttpSession session, @RequestBody Employee employee){
        R r = employeeService.login(employee);
        //登录成功就将用户保存到session中
        if (r.getCode()==1){
            Employee emp=(Employee)r.getData();
            session.setAttribute("employee",emp.getId());
        }
        return r;
    }

    /**
     * 注销
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.success("注销成功");
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @PostMapping
    public R save(@RequestBody Employee employee){
        if (employeeService.addEmployee(employee)){
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    /**
     * 查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(int page,int pageSize,String name){
        Page<Employee> pageInfo = employeeService.find(page, pageSize, name);
        return R.success(pageInfo);
    }

    /**
     * 修改
     * @param employee
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee){
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }

}
